<?php
namespace lib\capcha;
class capcha
{
    private $h_img;
    private $code_num;
    private $business;
    public function __construct($business,$code_num=4)
    {
        $this->code_num=$code_num;
        $this->business=$business;
        $this->h_img=imagecreatefromjpeg(WEBROOT.'/static/img/verify/'.strval(rand(1,8)).'.jpg');
    }                   //imagecratefromjpeg 输出一张jpg格式的图片

    public function draw_code()
    {
        //生成验证码
        $code=$this->create_code();
        //保存验证码
        $_SESSION['code_'.$this->business]=$code;
        //画验证码
        $this->draw($code);
        //画干扰线
        $this->disturb();
        //输出
        $this->print_out();
    }

    private function disturb()
    {
        $rnd=rand(5,10);
        for ($i = 0; $i < $rnd; $i++)
        {
            $linecolor = imagecolorallocate($this->h_img, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));
            imageline($this->h_img, mt_rand(1, 199), mt_rand(1, 79), mt_rand(1, 99), mt_rand(1, 79), $linecolor);
        }
    }

    private function print_out()
    {
        header('Content-type:image/png');
        imagepng($this->h_img);
    }

    private function draw($code)
    {
        for($i=0;$i<$this->code_num;$i++)
        {
            $fontsize = rand(35,40);        //字的大小
            $fontcolor = imagecolorallocate($this->h_img, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));   //分配颜色
            $fontcontent = $code{$i};
            // 显示的坐标
            $x = ($i * 200 / $this->code_num) + mt_rand(5, 10)+$fontsize-30;
            $y = mt_rand(50, 80);

            imagefttext($this->h_img,$fontsize,rand(0,45),
                $x,$y,$fontcolor,
                WEBROOT.'/static/font/en/'.strval(rand(1,6)).'.ttf',
                $fontcontent);      //1为图片 2为字体大小  3为斜率  4 x轴   5 y轴  6颜色 7字体格式  8 写东西
        }
    }

    private function create_code()
    {
        $str='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

        $code='';
        for($i=0;$i<$this->code_num;$i++)
        {
            $code.=$str{rand(0,strlen($str)-1)};
        }

        return $code;
    }

    public function __destruct()
    {
        imagedestroy($this->h_img);
    }


    public static function CompareCode($business,$code)
    {
        if(!$code) return false;

        $rtl=(strtolower($_SESSION['code_'.$business])==strtolower($code));
        unset($_SESSION['code_'.$business]);
        return $rtl;
    }
}
